<script setup lang="ts">
import CharacterTable from '@/components/symmetry/CharacterTable.vue'
import MatrixRepresentationsTable from '@/components/symmetry/MatrixRepresentationsTable.vue'
import PointGroupTree from '@/components/symmetry/PointGroupTree.vue'
import SymmetryOperationsTable from '@/components/symmetry/SymmetryOperationsTable.vue'
import LoadingOverlay from '@/components/ui/LoadingOverlay.vue'
import { request } from '@/network/axios'
import type { PointGroupDetail } from '@/types/symmetry'
import { formatInternational, formatSchoenflies } from '@/utils/formatters'
import { renderInline } from '@/utils/katex'
import { useIntersectionObserver } from '@vueuse/core'
import { computed, ref, useTemplateRef } from 'vue'
import { useRequest } from 'vue-hooks-plus'
import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router'

const route = useRoute()
const { t } = useI18n()

const activeSection = ref('character-table')
const isManualScrolling = ref(false)
let scrollTimeout: ReturnType<typeof setTimeout> | null = null

const { data: group, loading } = useRequest(() => request<PointGroupDetail>(`/symmetry/point-groups/${route.params.groupId}`), {
  onError: e => console.error(e)
})

// Section Refs
const characterTableRef = useTemplateRef<HTMLElement>('characterTableRef')
const symmetryOperationsRef = useTemplateRef<HTMLElement>('symmetryOperationsRef')
const matrixRepresentationsRef = useTemplateRef<HTMLElement>('matrixRepresentationsRef')
const relationshipTreeRef = useTemplateRef<HTMLElement>('relationshipTreeRef')

// Unified observer for all sections
useIntersectionObserver(
  [characterTableRef, symmetryOperationsRef, matrixRepresentationsRef, relationshipTreeRef],
  entries => {
    if (isManualScrolling.value) return
    const entry = entries.find(e => e.isIntersecting)
    if (entry) activeSection.value = entry.target.id
  },
  { rootMargin: '-10% 0px -80% 0px' }
)

const navItems = computed(() => {
  if (!group.value) return []
  return [
    { id: 'character-table', label: t('views.pointGroupDetail.characterTable.title') },
    { id: 'symmetry-operations', label: 'Symmetry Operations' },
    { id: 'matrix-representations', label: 'Matrix Representations' },
    ...(group.value.isCrystallographic ? [{ id: 'relationship-tree', label: t('views.pointGroupDetail.relationships') }] : [])
  ]
})

const scrollToSection = (id: string) => {
  activeSection.value = id
  isManualScrolling.value = true

  if (scrollTimeout) clearTimeout(scrollTimeout)
  scrollTimeout = setTimeout(() => (isManualScrolling.value = false), 1000)

  document.getElementById(id)?.scrollIntoView({ behavior: 'smooth' })
}
</script>

<template>
  <div class="relative min-h-35 space-y-8 pb-12">
    <LoadingOverlay v-if="loading" />

    <template v-if="group">
      <!-- Top Info Card -->
      <div class="card bg-base-100 border-base-300 border shadow-md">
        <div class="card-body">
          <h2 class="card-title gap-2">
            <span class="text-primary text-4xl font-bold" v-html="renderInline(formatSchoenflies(group.schoenflies))"></span>
            (
            <span v-if="group.international" v-html="renderInline(formatInternational(group.international))"></span>
            )
          </h2>

          <!-- Key-Value Info -->
          <div class="flex flex-wrap gap-3">
            <div class="badge badge-soft badge-lg">
              <span class="text-base-content/70">{{ t('symmetry.pointGroup.type') }}:</span>
              <span class="font-bold">{{ group.isCrystallographic ? t('symmetry.pointGroup.crystallographic') : t('symmetry.pointGroup.nonCrystallographic') }}</span>
            </div>

            <div class="badge badge-soft badge-lg">
              <span class="text-base-content/70">{{ t('symmetry.pointGroup.name') }}:</span>
              <span class="font-bold">{{ group.name }}</span>
            </div>

            <div class="badge badge-soft badge-lg">
              <span class="text-base-content/70">{{ t('symmetry.pointGroup.order') }}:</span>
              <span class="font-bold">{{ group.order }}</span>
            </div>

            <div v-if="group.crystalSystem" class="badge badge-soft badge-lg">
              <span class="text-base-content/70">{{ t('symmetry.pointGroup.crystalSystem') }}:</span>
              <span class="font-bold">{{ group.crystalSystem }}</span>
            </div>

            <div v-if="group.laueClass" class="badge badge-soft badge-lg">
              <span class="text-base-content/70">{{ t('symmetry.pointGroup.laueClass') }}:</span>
              <span class="font-bold" v-html="renderInline(formatInternational(group.laueClass))"></span>
            </div>

            <div v-if="group.family" class="badge badge-soft badge-lg">
              <span class="text-base-content/70">{{ t('symmetry.pointGroup.family') }}:</span>
              <span class="font-bold">{{ group.family }}</span>
            </div>

            <div v-if="group.parity" class="badge badge-soft badge-lg">
              <span class="text-base-content/70">{{ t('symmetry.pointGroup.parity') }}:</span>
              <span class="font-bold">{{ group.parity }}</span>
            </div>

            <div v-if="group.parameterDescription" class="badge badge-soft badge-lg">
              <span class="text-base-content/70">{{ t('symmetry.pointGroup.parameterDescription') }}:</span>
              <span class="font-bold">{{ group.parameterDescription }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- Sticky Navigation Bar -->
      <div class="bg-base-300/50 flex-center sticky top-20 z-2 mx-auto w-fit gap-2 overflow-x-auto rounded-full p-1 backdrop-blur-md">
        <button
          v-for="item in navItems"
          :key="item.id"
          @click="scrollToSection(item.id)"
          class="btn rounded-full transition-all"
          :class="[activeSection === item.id ? 'btn-neutral' : 'hover:bg-base-content/10 border-none bg-transparent']"
        >
          {{ item.label }}
        </button>
      </div>

      <!-- Character Table -->
      <div class="card bg-base-100 border-base-300 border shadow-md">
        <div class="card-body">
          <h2 id="character-table" ref="characterTableRef" class="card-title scroll-mt-40">{{ t('views.pointGroupDetail.characterTable.title') }}</h2>
          <CharacterTable :schoenflies="group.schoenflies" :character-table="group.characterTable" />
        </div>
      </div>

      <!-- Symmetry Operations -->
      <div class="card bg-base-100 border-base-300 border shadow-md">
        <div class="card-body">
          <h2 id="symmetry-operations" ref="symmetryOperationsRef" class="card-title scroll-mt-40">Symmetry Operations</h2>
          <SymmetryOperationsTable :group="group" />
        </div>
      </div>

      <!-- Matrix Representations -->
      <div class="card bg-base-100 border-base-300 border shadow-md">
        <div class="card-body">
          <h2 id="matrix-representations" ref="matrixRepresentationsRef" class="card-title scroll-mt-40">Matrix Representations</h2>
          <MatrixRepresentationsTable :group="group" />
        </div>
      </div>

      <PointGroupTree v-if="group.isCrystallographic" :highlight-group-id="group.groupId" id="relationship-tree" ref="relationshipTreeRef" class="section-anchor scroll-mt-40" />
    </template>

    <!-- Error State -->
    <div v-else-if="!loading" class="flex-center flex-1 flex-col gap-4">
      <div class="text-6xl">⚠️</div>
      <h2 class="text-2xl font-bold">{{ t('views.pointGroupDetail.notFound.title') }}</h2>
      <router-link to="/point-groups" class="btn btn-primary">{{ t('views.pointGroupDetail.backToList') }}</router-link>
    </div>
  </div>
</template>
